﻿using System;
using System.Collections.Generic;
using System.Text;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
namespace SharpScriptLib
{
    public class SharpScriptLib
    {
        static public Assembly CompileFromSource(CompilerParameters Params, params string[] Sources)
        {
            try
            {
                CodeDomProvider CodeProvider = new CSharpCodeProvider();
                CompilerResults CompilerRes = CodeProvider.CompileAssemblyFromSource(Params, Sources);
                if (CompilerRes.Errors.HasErrors)
                {
                    string ExceptionMsg = string.Format("Filename:{0} Column:{1} \n Error:{2} Message:{3}", CompilerRes.Errors[0].FileName, CompilerRes.Errors[0].Column, CompilerRes.Errors[0].ErrorNumber, CompilerRes.Errors[0].ErrorText);
                    Exception except = new Exception(ExceptionMsg);
                    throw except;
                }
                return CompilerRes.CompiledAssembly;
            }
            catch (Exception ex) { throw ex; }
        }
        static public Assembly CompileFromFile(CompilerParameters Params, params string[] FileNames)
        {
            try
            {
                CodeDomProvider CodeProvider = new CSharpCodeProvider();
                CompilerResults CompilerRes = CodeProvider.CompileAssemblyFromFile(Params, FileNames);
                if (CompilerRes.Errors.HasErrors)
                {
                    string ExceptionMsg = string.Format("Filename:{0} Column:{1} \n Error:{2} Message:{3}", CompilerRes.Errors[0].FileName, CompilerRes.Errors[0].Column, CompilerRes.Errors[0].ErrorNumber, CompilerRes.Errors[0].ErrorText);
                    Exception except = new Exception(ExceptionMsg);
                    throw except;
                }

                return CompilerRes.CompiledAssembly;
            }
            catch (Exception ex) { throw ex; }
        }
        static public void Run(string AppDomainName, string FileName, string[] Args)
        {
            try
            {
                AppDomain App = AppDomain.CreateDomain(AppDomainName);
                App.ExecuteAssembly(FileName, null, Args);
            }
            catch (Exception ex) { throw ex; }
        }
        static public object InvokeMethod(Assembly asm, string ClassName, string MethodName, object[] Params)
        {
            try
            {
                Type type = asm.GetType(ClassName);
                object Targert = Activator.CreateInstance(type);
                return type.InvokeMember(MethodName, BindingFlags.Default | BindingFlags.InvokeMethod, null, Targert, Params);
            }
            catch (Exception ex) { throw ex; }
        }
    }
}